package com.study;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-13 14:59
 * @version: 1.0
 * @description: 子数组最大平均数
 * 给定一个数组，找出平均数最大且长度为K的连续子数组最大平均值
 **/
public class AvgArray {

    public static void main(String[] args) {
        int[] arr = {1,12,-5,-6,50,3};
//        int[] arr = {6,3,5,7,2,8,4};
        System.out.println(findMaxAvg(arr,4));


    }

    private static double findMaxAvg(int[] arr, int len) {
        int sum = 0,max = 0;
        for (int low = 0,high = 0; high < arr.length ; ) {
            if (high - low >= len){
                sum = sum + arr[high++] - arr[low++];
                max = Math.max(max,sum);
            }else {
                sum += arr[high++];
                max = sum;
            }

        }
        return max * 1.0/len;
    }

    private static double findMaxAvg1(int[] arr, int len) {
        int sum = 0,max = 0;
        for (int low = 0,high = 0; high < arr.length; ) {
            if (high - low == len){
                sum = sum + arr[high++] - arr[low--];
                max = Math.max(sum,max);
            }else {
                sum += arr[high++];
            }
        }
        return max * 1.0 / len;
    }
}
